from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain_community.llms import OpenAI  # 或其他模型
from langchain_core import output_parsers
from langchain_core.output_parsers import StrOutputParser
import re
import os
os.environ["OPENAI_API_KEY"] = "sk-fhfopxxokpblqjbivoyhwhftlbjwrgeddccbytodqipkaqum"
base_url="https://api.siliconflow.cn/v1"
# 配置 SiliconFlow 的 OpenAI 兼容 API
llm = OpenAI(
    openai_api_base=base_url,
    api_key=os.environ.get("OPENAI_API_KEY"),
    # 不是推理模型
    #model_name="Qwen/Qwen3-235B-A22B",
    model_name="THUDM/GLM-4-9B-0414",
    temperature=0.1,
    top_p=0.1,
    max_tokens=1024
)
# 提示词工程
ANALOGY_PROMPT = PromptTemplate(
    input_variables=["concept", "difficulty"],
    template="""
    请用生活化的比喻解释{concept}概念，面向{difficulty}理解水平的受众。
    要求：
    1. 用不超过2句话的比喻
    2. 给出3个核心要点（带emoji图标）
    3. 生成1道选择题
    4. 不要markdown格式输出
    5. 只生成一个json对象
    
    示例格式：
    {{
        "id": uuid随机数,
        "name": {concept},
        "emoji": "⏱️",
        "difficulty": 等级数字,
        "analogy": "比喻内容...",
        "key_points": ["要点1", "要点2", "要点3"],
        "quiz": {{
            "question": "问题文本",
            "options": [
                {{"text": "选项1", "correct": true/false}},
                {{"text": "选项2", "correct": true/false}}
            ]
        }}
    }}
    """
)

def test(aaaa):
    print("test1")
    print(aaaa)

str_output_parser = StrOutputParser()   
def generate_concept_explanation(concept, difficulty):
    
    chain = LLMChain(
        llm=llm,
        prompt=ANALOGY_PROMPT,
        output_key="result"
    )
    
    response = chain.run({
        "concept": concept,
        "difficulty": difficulty
    })

    print(response,flush=True)  # 打印LLM返回的内容 (optiona)
    #LLM返回的内容 (optiona)
    match = re.search(r'\{.*?\}', response, re.DOTALL)
    if match:
        try:
            json = json.loads(match.group(0))  
        except json.JSONDecodeError:
            return json.loads(match.group(1))
        return json
    else:
        return ""
   

if __name__ == '__main__':
    generate_concept_explanation("区块链","普通人")